import requests
import pyaudio
import asyncio
import logging

async def play_audio_from_stream(url, data, chunk_size=8192):
    response = requests.get(url, data=data, stream=True)
    audio_data = bytearray()
    n_channels = 1
    samp_width = 2
    framerate = 22050
    try:
        if response.status_code == 200:
            p = pyaudio.PyAudio()
            stream = p.open(format=p.get_format_from_width(samp_width),
                            channels=n_channels,
                            rate=framerate,
                            output=True)
            for chunk in response.iter_content(chunk_size=chunk_size):
                if chunk:
                    stream.write(chunk)
                    audio_data.extend(chunk)
                    await asyncio.sleep(0)
            stream.stop_stream()
            stream.close()
            p.terminate()
            return bytes(audio_data)
        else:
            logging.error(f"请求失败: 状态码 {response.status_code}，无法获取到音频数据进行播放")
            return None
    except Exception as e:
        logging.error(f"音频播放出现错误: {e}")
        return None